import Bezier from "./Bezier";
import line from "./line";
import pos_ui from "./pos_ui";

const { ccclass, property } = cc._decorator;

@ccclass
export default class bezier_manager extends cc.Component {

    @property({ type: cc.Prefab, tooltip: '贝塞尔的预制体' })
    bezier_prefab: cc.Prefab = null;

    @property({ type: cc.Node, tooltip: '贝塞尔的父节点' })
    bezier_parent: cc.Node = null;

    @property({ type: cc.Sprite, tooltip: '背景' })
    bg: cc.Sprite = null;

    @property({ type: pos_ui, tooltip: '选择坐标框' })
    pos_ui: pos_ui = null;

    @property({ type: cc.Prefab, tooltip: '运动小球' })
    ball: cc.Prefab = null;

    /** 新建的贝塞尔个数 */
    private bezier_number: number = 0;

    /** 全部的贝塞尔数组 */
    private bezier_array: cc.Node[] = [];

    /** 贝塞尔曲线直线的显示与否 */
    private show_bezier: boolean = true;

    /** 当前的贝塞尔选择点 */
    private bezier_no: number = 0;

    // onLoad () {}

    start() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.on_hide_bezier_ui, this);

        this.new_bezier();

        let self = this;

        document.addEventListener("drop", function (event: DragEvent) {
            event.preventDefault();//阻止拖拽结束的默认打开行为
            let data = event.dataTransfer.files[0];
            let file = new FileReader();
            file.readAsDataURL(data);

            console.log('??', file);

            //要等filereader文件打开后才能够成功读取到文件
            file.onload = function (event) {

                let img = new Image;
                img.src = (event.target.result as string);

                let a = new cc.Texture2D;
                a.initWithElement(img);

                let spriteframe = new cc.SpriteFrame;
                spriteframe.setTexture(a);

                self.bg.spriteFrame = spriteframe;
            }
        })
        document.addEventListener("dragover", function (event: DragEvent) {
            event.preventDefault();//阻止拖拽结束的默认打开行为
        })

        this.node.on('move_', (event: cc.Event.EventCustom) => {
            let data = event.getUserData();
            if (data.no === (this.bezier_no + 1)) {
                this.pos_ui.update_pos(data.pos);
            } else {
                this.change_bezier_no((data.no));
            }
            // this.pos_ui.update_pos(data.pos);
            event.stopPropagation();
        });
    }

    /**
     * 新增贝塞尔曲线
     */
    new_bezier() {
        //当贝塞尔曲线大于1，就生成一个
        let poi: cc.Vec2 = null;
        if (this.bezier_number >= 1) {
            poi = this.bezier_array[this.bezier_number - 1].getComponent(line).return_end_poi();
        }

        this.bezier_number++;
        let the_bezier: cc.Node = cc.instantiate(this.bezier_prefab);
        the_bezier.parent = this.bezier_parent;


        the_bezier.getComponent(line).new_graphics(this.bezier_number, this.show_bezier, poi);
        this.bezier_array.push(the_bezier);
    }

    /**
     * 删除贝塞尔曲线
     */
    declare_bezier() {
        if (this.bezier_number < 0) {
            return;
        }

        this.bezier_number--;
        this.bezier_array[this.bezier_number].destroy();
        this.bezier_array.splice(this.bezier_number, 1);
    }

    /**
     * 对齐贝塞尔曲线(头围相接)
     */
    widget_bezier() {
        for (let i = 0; i < this.bezier_number; i++) {
            if (i == 0) {
                continue;
            }

            let first_poi = this.bezier_array[i - 1].getComponent(line).return_all_poi()[1];
            this.bezier_array[i].getComponent(line).start_widet_poi(first_poi);

            if (i == (this.bezier_number - 1)) {
                let first_poi = this.bezier_array[0].getComponent(line).return_all_poi()[0];
                this.bezier_array[i].getComponent(line).end_widget_poi(first_poi);
            }
        }
    }

    //导出数据
    saveJSON() {
        let filename = 'poi.json';
        let data: cc.Vec2[][] = [];
        for (let i = 0; i < this.bezier_array.length; i++) {
            let poi = this.bezier_array[i].getComponent(line).return_all_poi();
            data.push(poi);
        }

        let data_: any = data;

        if (typeof data_ === 'object') {
            data_ = JSON.stringify(data_, undefined, 4);
        }
        var blob = new Blob([data_], { type: 'text/json' }),
            e = document.createEvent('MouseEvents'),
            a = document.createElement('a')
        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        a.dispatchEvent(e)
    }

    /**
     * 开启关闭贝塞尔的直线连接
     */
    switch_bezier() {
        this.show_bezier = !this.show_bezier;
        for (let i = 0; i < this.bezier_number; i++) {
            this.bezier_array[i].getComponent(line).switch_line();
        }
    }

    /**
     * 显示当前最后一位的数据ui
     */
    on_show_pos_ui() {
        if (this.bezier_number < 0) {
            console.error('没有贝塞尔曲线了');
            return;
        }
        this.bezier_no = 0;
        this.pos_ui.show_ui(1, this.bezier_array[this.bezier_no].getComponent(line).return_all_poi());
    }


    /**
     * 动起来
     */
    on_run() {
        let ball = cc.instantiate(this.ball);
        ball.parent = this.bezier_parent;
        let data: cc.Vec2[][] = [];
        for (let i = 0; i < this.bezier_array.length; i++) {
            let poi = this.bezier_array[i].getComponent(line).return_all_poi();
            data.push([poi[0], poi[2], poi[1]]);

        }

        // let actions = data.map(param => {
        //     return cc.bezierTo(1, param);
        // });
        // ball.runAction(cc.sequence(actions));
        let self = this;
        let index = 0;
        let playAction = () => {
            let param = data[index++];
            let callFunc = () => {
                if (index >= data.length) {
                    cc.log('播放完毕');
                    return;
                }
                playAction();
            };
            cc.tween(ball).bezierTo(1, param[0], param[1], param[2]).call(callFunc).start();
        }
        playAction();
    }

    on_run2() {
        let ball = cc.instantiate(this.ball);
        ball.parent = this.bezier_parent;
        let bezierCurveLists = [];
        for (let i = 0; i < this.bezier_array.length; i++) {
            let poi = this.bezier_array[i].getComponent(line).return_all_poi();
            bezierCurveLists.push([poi[0], poi[2], poi[1]]);
        }
        let bezierCurveData = this.getBezierCurveData(bezierCurveLists, 1)

        this.computeBezierActions(bezierCurveData, ball)
        // console.log("保存路径pointCurveDict->", pointCurveDict)
    }

    //time(每个贝塞尔的平均时长)
    getBezierCurveData(bezierCurveLists, time: number): { time: number, length: number, points: Array<any> } {
        let pointCount = 100;// 每段曲线的切割份数

        let bezierCurveData = {
            time: 0,//运行总时长
            length: 0,//曲线总长
            points: [],//曲线点列表
        }
        bezierCurveData.length = 0;
        bezierCurveData.points = [];
        console.log("保存路径bezierLists", bezierCurveLists);
        for (var i = 0, len = bezierCurveLists.length; i < len; i++) {
            const bezier = bezierCurveLists[i];
            // 创建一个贝塞尔曲线
            // let bezierCurve = new Bezier(bezier.start, bezier.control, bezier.end, 100);
            // console.log("consscscds", Object.values(bezier));

            let bezierCurve = new Bezier(Object.values(bezier), 2);

            // 获取曲线点
            let points = bezierCurve.getPoints(pointCount);
            console.log("consscscds", pointCount);

            // 获取曲线长度
            let curveLength = bezierCurve.getCurveLength();
            // 计算路程长度
            bezierCurveData.length += curveLength;
            // 存储曲线点
            bezierCurveData.points.push(...points);
            // console.log("points", points);
            bezierCurveData.time += time;
        }
        console.log("保存路径bezierCurveData", bezierCurveData);
        return bezierCurveData;
    }

    computeBezierActions(bezierCurveData, box: cc.Node) {
        let actionLists = [];
        // 创建动作队列
        for (var i = 0, len = bezierCurveData.points.length; i < len; i++) {
            const point = bezierCurveData.points[i];
            //计算当前路段需要的时间
            let time = point.length / bezierCurveData.length * bezierCurveData.time;
            point.time = time;
            // 创建动作
            let action = cc.moveTo(time, cc.v2(point.x, point.y));
            actionLists.push(action);
        }
        if (actionLists.length > 1) {
            box.runAction(cc.sequence(actionLists));
        } else {
            box.runAction(actionLists[0]);
        }
    }

    /**
     * 隐藏贝塞尔ui事件
     */
    on_hide_bezier_ui() {
        console.log('点了关闭？')
        this.pos_ui.hide_ui();
    }

    /**
     * 接受新的节点信息
     */
    set_now_pos(pos: cc.Vec2[]) {
        this.bezier_array[this.bezier_no].getComponent(line).change_pos(pos);
    }

    /**
     * 跳转到新的贝塞尔显示
     */
    change_bezier_no(number: number) {
        number = Math.floor(number);
        if (number > this.bezier_number) {
            console.error('超出数组');
            return
        }
        if (number < 1) {
            console.error('不要输入比1小的数');
            return
        }
        number--;


        this.bezier_no = number;

        let pos = this.bezier_array[this.bezier_no].getComponent(line).return_all_poi();
        this.pos_ui.update_pos(pos, (this.bezier_no + 1));
    }

    // update (dt) {}
}
